package com.cross.mutil;

import com.cross.core.AbstractReader;
import com.cross.core.Header;
import com.cross.core.Reader;
import com.cross.core.Row;
import com.cross.exception.CrossException;

/**
 * 复合读入器:将多个读取器合并为一个。
 * 依次从多个读取器中读取数据
 * 
 * 2009-3-26
 * 
 * @author craziness_stone
 */
public class SimpleMutilReader extends AbstractReader {

	private Reader<Row>[] readers;

	private int index = 0;

	private Reader<Row> currentReader = null;

	public SimpleMutilReader(final Reader<Row>... readers)
			throws CrossException {
		if (readers == null) {
			throw new CrossException("空指针异常!");
		}
		this.readers = readers;
	}

	@Override
	protected boolean nextRow() {
		return nextRowImpl();
	}

	private boolean nextRowImpl() {
		if (currentReader != null && currentReader.hasNext()) {
			currentRow = currentReader.next();
			return true;
		}
		currentReader = nextReader();
		if (currentReader == null) {
			return false;
		}
		return nextRowImpl();
	}

	private Reader nextReader() {
		if (index >= readers.length) {
			return null;
		}
		if (readers[index++] == null) {
			return nextReader();
		}
		return readers[index];
	}

	private void initHeader(Header header){
		this.header.removeAll();
		
	}
	
	@Override
	public void close() {
		for (Reader r : readers) {
			if (r == null) {
				continue;
			}
			r.close();
		}
	}

}
